<script setup lang="ts">
import {computed, ref, useAttrs, useSlots, watch} from "vue";
import {ElDatePicker} from "element-plus";
import {devDateTimeProps} from './datePicker';
import {devDeepMerge, useConfig} from "@/index";

const attrs = useAttrs();
const slots = useSlots();
const props = defineProps(devDateTimeProps);
const emit = defineEmits(['update:startTime', 'update:endTime', 'update:modelValue', 'change']);

const defaultElDatePickerProps = useConfig().elDatePickerProps;
// 使用计算属性获取响应式配置
const mergedConfig = computed(() => devDeepMerge(defaultElDatePickerProps, attrs,['modelValue']));
const pickerType = computed(() => mergedConfig.value.type || 'date');
const isRangeType = computed(() => ['datetimerange', 'daterange', 'monthrange'].includes(pickerType.value));

// 主值绑定
const dateValue = ref<any>(null);

// 值转换逻辑
const parseValue = (value: any) => {
  if (!isRangeType.value) return value;
  if (props.separateBinding && value === null) {
    return [props.startTime ?? null, props.endTime ?? null];
  }
  return Array.isArray(value) ? [...value] : null;
};

// 统一更新逻辑
const updateValues = (newVal: any) => {
  if (isRangeType.value) {
    const rangeValue = Array.isArray(newVal) && newVal.length === 2 ? newVal : [null, null];

    // 同步更新逻辑
    if (props.separateBinding) {
      emit('update:startTime', rangeValue[0]);
      emit('update:endTime', rangeValue[1]);
    }
    emit('update:modelValue', newVal);
    emit('change', {
      startTime: rangeValue[0],
      endTime: rangeValue[1],
      modelValue: newVal
    });
  } else {
    emit('update:modelValue', newVal);
    emit('change', { modelValue: newVal });
  }
};

// 处理日期变化
const handleChange = (val: any) => {
  dateValue.value = val;
  updateValues(val);
};

// 响应外部值变化
watch([
  () => props.modelValue,
  () => props.startTime,
  () => props.endTime
], ([modelVal, startVal, endVal]) => {
  if (isRangeType.value && props.separateBinding) {
    dateValue.value = [startVal, endVal];
  } else {
    dateValue.value = parseValue(modelVal);
  }
}, { immediate: true, deep: true });

defineOptions({ name: 'DevDatePicker',  inheritAttrs: false });
</script>

<template>
  <el-date-picker
      v-model="dateValue"
      v-bind="mergedConfig"
      @change="handleChange"
  >
    <template v-for="(_, name) in slots" #[name]="scope">
      <slot :name="name" v-bind="scope" />
    </template>
  </el-date-picker>
</template>
